package com.MusicWeb.servlet;

import com.MusicWeb.entity.UserInformation;
import com.MusicWeb.service.UserinformationService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/SubmitServlet/josn")
public class SubmitServlet extends HttpServlet {
    UserinformationService userinformationService = new UserinformationService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //从网页获取用户的信息
        String name = req.getParameter("name");
        Integer age = Integer.valueOf(req.getParameter("age"));
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        Integer userid = Integer.valueOf(req.getParameter("userid"));

        UserInformation userInformation = new UserInformation();
        userInformation.setName(name);
        userInformation.setAge(age);
        userInformation.setSex(sex);
        userInformation.setPhone(phone);
        userInformation.setEmail(email);
        userInformation.setUserid(userid);

        if (userinformationService.Userinformation(userInformation) != null) {
            // 设置返回的数据为json对象
            resp.setContentType("application/json;charset=utf-8");
            // 把实体转换为json，返回给前端
            String str = new Gson().toJson(userInformation);
            resp.getWriter().print(str);
            req.getSession().setAttribute("msg", "提交成功");
//            resp.sendRedirect(req.getContextPath() + "/test.jsp");
        } else {
            req.getSession().setAttribute("msg", "提交失败");
//            resp.sendRedirect(req.getContextPath() + "/test.jsp");
        }


    }
}
